package com.flag.liutao.modules.upload.controller;


import cn.hutool.http.HttpRequest;
import com.flag.liutao.common.domain.ResponseResult;
import com.flag.liutao.common.utils.JwtUtil;
import com.flag.liutao.common.utils.MyImgUtil;
import com.flag.liutao.modules.user.domain.User;
import com.flag.liutao.modules.user.service.IUserService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/admin/upload")
@Slf4j
@Api("文件管理")
public class UploadController {

    @Autowired
    private MyImgUtil myImgUtil;
    @Autowired
    private IUserService userService;



    @PostMapping("avatar")
    @PreAuthorize("hasAuthority('sys_power:user_U')")
    @ApiOperation(value="修改用户头像",notes = "文件管理：修改用户头像")
    public ResponseResult<Map> avatar(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        String name = myImgUtil.upload(file);
        map.put("file",name);

        String authorization = request.getHeader("Authorization");
        String token = authorization.split(" ")[1];
        String uid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            uid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token认证失败");
        }

        User user = new User();
        user.setId(Long.valueOf(uid));
        user.setAvatar(name);
        userService.updateById(user);
        return ResponseResult.ok(map);

    }
}
